document.addEventListener('DOMContentLoaded', function() {
    const productId = new URLSearchParams(window.location.search).get('id');
    if (!productId) {
        alert('无效的商品ID');
        return;
    }

    // 发送 axios 请求获取商品详情
    axios.get(`/product/${productId}`)
        .then(response => {
            const product = response.data;
            document.getElementById('product-name').textContent = product.name;
            document.getElementById('product-image').src = product.image;
            document.getElementById('product-description').textContent = product.description;
            document.getElementById('product-price-value').textContent = product.price;

            // 处理加入购物车按钮点击事件
            document.getElementById('add-to-cart').addEventListener('click', function() {
                const productName = document.getElementById('product-name').textContent;
                const productPrice = document.getElementById('product-price-value').textContent;
                const productImage = document.getElementById('product-image').src;
                const productNumber = 1; // 假设每次添加一个商品

                // 发送请求到后端服务器，将商品信息添加到购物车
                axios.post('/add-to-cart', {
                    productId: productId,
                    productName: productName,
                    productPrice: productPrice,
                    productImage: productImage,
                    productNumber: productNumber
                }).then(response => {
                    if (response.data.success) {
                        alert('商品已成功添加到购物车！');
                        // 更新购物车数量
                        const cartCountElement = document.querySelector('.orange-nav-right .cart i');
                        cartCountElement.innerText = `购物车(${response.data.cartCount})`;
                    } else {
                        alert('添加商品到购物车失败：' + response.data.message);
                    }
                }).catch(error => {
                    alert('网络错误，请稍后再试！');
                });
            });
        })
        .catch(error => {
            alert('获取商品详情出错: ' + error.message);
        });
});